#include "CommitteeManager.h"

#include <fstream>
#include <boost/foreach.hpp>
#include "Helpers.h"

bool CommitteeManager::serialize( const std::string& fileName ) const
{
  if (fileName.empty())
    return false;
  std::ofstream stream(fileName.c_str());
  toStream(stream);
  return true;
}

void CommitteeManager::toStream(std::ostream& stream) const
{
  for (CommitteeMap::const_iterator it = m_committees.begin(); it != m_committees.end(); ++it)
    stream << (*it).second;
}

std::string CommitteeManager::toString() const
{
  std::ostringstream stream;
  toStream(stream);
  return stream.str();
}

bool CommitteeManager::deserialize( const std::string& fileName )
{
  if (fileName.empty())
    return false;
  m_committees.clear();
  std::ifstream stream(fileName.c_str());
  while (!stream.eof())
  {
    Committee committee;
    stream >> committee; 
    if (!committee.empty())
      m_committees.insert(CommitteePair(committee.id(), committee));
  }
  return true;
}

const Committee *CommitteeManager::committeeById(const std::string &id) const
{
  CommitteeMap::const_iterator found = m_committees.find(id);
  if (found != m_committees.end())
    return &((*found).second);
  return 0;
}

std::string CommitteeManager::newCommitteeId() const
{
  int numericMax = -1;
  BOOST_FOREACH(const CommitteePair &p, m_committees)
  {
    if (as<int>(p.first) > numericMax)
      numericMax = as<int>(p.first);
  }
  return asString(numericMax + 1);  
}